package com.ruoyi.framework.sharding;


import java.util.*;

/**
 * @Description: 分片表缓存枚举
 * @Author WangHan
 * @Date 2024/9/19 15:16
 * @Version 1.0
 */
public enum ShardingTableCache {

    /**
     * 通知公告表
     */
    SYS_NOTICE("sys_notice", new HashSet<>()),

    /**
     * JOB表
     */
    SYS_JOB("sys_job", new HashSet<>());


    /**
     * 逻辑表名
     */
    private final String logicTableName;
    /**
     * 实际表名
     */
    private final Set<String> resultTableNamesCache;

    private static Map<String, ShardingTableCache> valueMap = new HashMap<>();

    static {
        Arrays.stream(ShardingTableCache.values()).forEach(o -> valueMap.put(o.logicTableName, o));
    }

    ShardingTableCache(String logicTableName, Set<String> resultTableNamesCache) {
        this.logicTableName = logicTableName;
        this.resultTableNamesCache = resultTableNamesCache;
    }

    public static ShardingTableCache of(String value) {
        return valueMap.get(value);
    }

    public String logicTableName() {
        return logicTableName;
    }

    public Set<String> resultTableNamesCache() {
        return resultTableNamesCache;
    }

    /**
     * 更新缓存、配置（原子操作）
     *
     * @param tableNameList
     */
    public void atomicUpdateCacheAndActualDataNodes(List<String> tableNameList) {
        synchronized (resultTableNamesCache) {
            // 删除缓存
            resultTableNamesCache.clear();
            // 写入新的缓存
            resultTableNamesCache.addAll(tableNameList);
            // 动态更新配置 actualDataNodes
            ShardingAlgorithmTool.actualDataNodesRefresh(logicTableName, tableNameList);
        }
    }

    public static Set<String> logicTableNames() {
        return valueMap.keySet();
    }

    @Override
    public String toString() {
        return "ShardingTableCache{" +
                "logicTableName='" + logicTableName + '\'' +
                ", resultTableNamesCache=" + resultTableNamesCache +
                '}';
    }

}
